package com.example.service.impl;

import com.example.entity.MessageNotice;
import com.example.entity.demandMaintance.DemandMaintanceApply;
import com.example.entity.training.TrainingPlan;
import com.example.ext.entity.ExtElevator;
import com.example.ext.entity.ExtParty;
import com.example.mapp.DemandMaintMapp;
import com.example.mapp.ElevatorMapp;
import com.example.mapp.MessageNoticeMapp;
import com.example.mapp.PartyMapp;
import com.example.service.DemandMaintanceService;
import com.example.util.ResultUtil;
import com.example.util.XmlFill;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DemandMaintanceServiceImpl implements DemandMaintanceService {

    private static final Logger logger = LoggerFactory.getLogger(DemandMaintanceServiceImpl.class);
    @Autowired
    private DemandMaintMapp demandMaintMapp;

    @Autowired
    private Environment environment;

    @Autowired
    private PartyMapp partyMapp;

    @Autowired
    private ElevatorMapp elevatorMapp;

    @Autowired
    private MessageNoticeMapp messageNoticeMapp;

    @Override
    public Map<String, Object> query(DemandMaintanceApply demandMaintanceApply) {
        Map<String,Object> resultMap = new HashMap<>();
        try{
            if((demandMaintanceApply.getCurrentPage()+"") != null && (demandMaintanceApply.getPageSize()+"") != null){
                Page<TrainingPlan> page = PageHelper.startPage(demandMaintanceApply.getCurrentPage(),demandMaintanceApply.getPageSize());
                List<DemandMaintanceApply> list = demandMaintMapp.query(demandMaintanceApply);
                resultMap.put("list",list);
                resultMap.put("total",page.getTotal());
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",resultMap);
    }

    @Override
    @Transactional
    public Map<String, Object> add(DemandMaintanceApply demandMaintanceApply) {
        try{
            demandMaintanceApply.setApplyStatus("0");
            demandMaintMapp.insert(demandMaintanceApply);

            /**
             * 给维保单位发送消息，上传维保申明文件
             */
            Map<String, Object> map = new HashMap<>();
            map.put("roleName", "%管理人员%");
            map.put("partyId", demandMaintanceApply.getMaintenancePartyId());
            List<String> users = partyMapp.queryUserList(map);

            for (String userId : users) {
                String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                MessageNotice msg = new MessageNotice();
                msg.setTitle("按需维保申请");
                msg.setContent("您有一份按需维保申请，需上传您单位的维保服务自我申明文件，请及时处理！");
                msg.setReceiveUserId(userId);
                msg.setIsRead("0");
                msg.setNoticeTime(noticeTime);
                msg.setSendUserId(demandMaintanceApply.getUserPartyId());
                msg.setReceivePartyId(demandMaintanceApply.getMaintenancePartyId());
                messageNoticeMapp.add(msg);
            }
            return ResultUtil.returnSuccess("新增成功", null);
        }catch (Exception e){
            logger.error("按需维保申请记录添加失败！",e);
            return ResultUtil.returnError("新增失败",null);
        }
    }

    /**
     * 生成承诺书文件
     * @return
     */
    @Override
    public Map<String,Object> exportLetterOfCommitmentDoc(DemandMaintanceApply demandMaintanceApply){
        Map<String, Object> result = new HashMap<>();
        String path = environment.getProperty("upload", String.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(new Date());
        if (path.endsWith(File.separator)) {
            path = path + dateString + File.separator;
        } else {
            path = path + File.separator + dateString + File.separator;
        }
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        // 重现生成文件名，防止中文乱码
        String fileName = UUID.randomUUID() + ".docx";
        path = path + fileName;
        result.put("fileUrl", dateString + File.separator + fileName);
        result.put("fileName", "电梯按需维保试点工作承诺书.docx");
        try{
            /**
             * 查询按需维保结果，生成承诺书。
             */
            Map<String, String> data = new HashMap<>();
            data.put("userPartyName", demandMaintanceApply.getUserPartyName());
            data.put("maintenancePartyName", demandMaintanceApply.getMaintenancePartyName());
            data.put("createCompanyName", demandMaintanceApply.getCreateCompanyName());
            //获取使用单位与维保单位的联系人信息
            ExtParty party1 = partyMapp.queryById(demandMaintanceApply.getUserPartyId());
            ExtParty party2 = partyMapp.queryById(demandMaintanceApply.getMaintenancePartyId());
            if(party1 != null){
                data.put("contacts1",party1.getContacts() != null ? party1.getContacts() : "");
                data.put("contactsMobile1",party1.getContactsMobile() != null ? party1.getContactsMobile() : "");
            }
            if(party2 != null){
                data.put("contacts2",party2.getContacts() != null ? party2.getContacts() : "");
                data.put("contactsMobile2",party2.getContactsMobile() != null ? party2.getContactsMobile() : "");
            }

            /**
             * 组装动态表格数据
             */
            Map<String,Object> mapParams = new HashMap<>();
            //获取添加的电梯
            ExtElevator elevator = new ExtElevator();
            elevator.setElevatorIds(Arrays.asList(demandMaintanceApply.getElevatorIds().split(",")));
            List<ExtElevator> elevators = elevatorMapp.demandMaintGetElevators(elevator);
            List<String[]> elevatorList = new ArrayList<>();
            for(int i = 0,len = elevators.size(); i < len; i++){
                ExtElevator elevator1 = elevators.get(i);
                elevatorList.add(new String[]{(i+1)+"",elevator1.getElevatorNum(),elevator1.getElevatorTypeName(),elevator1.getBuildAddr()});
                if(i == 0){
                    data.put("index",(i+1)+"");
                    data.put("elevatorNum",elevator1.getElevatorNum() != null ? elevator1.getElevatorNum() : "");
                    data.put("elevatorTypeName",elevator1.getElevatorTypeName() != null ? elevator1.getElevatorTypeName() : "");
                    data.put("buildAddr",elevator1.getBuildAddr() != null ? elevator1.getBuildAddr() : "");
                }

            }
            mapParams.put("elevatorList",elevatorList);
            //先取第一行
            if(StringUtils.isNotEmpty(demandMaintanceApply.getInsuranceName())){
                List<String> insuranceNames = Arrays.asList(demandMaintanceApply.getInsuranceName().split("\\|"));
                List<String> insuranceDates = Arrays.asList(demandMaintanceApply.getInsuranceDate().split("\\|"));
                List<String[]> insuranceList = new ArrayList<>();

                for(int j = 0,len = insuranceNames.size(); j < len; j++){
                    String insuranceName = insuranceNames.get(j);
                    String insuranceDate = insuranceDates.get(j);
                    insuranceList.add(new String[]{"电梯安全综合保险承保单位",insuranceName});
                    insuranceList.add(new String[]{"电梯安全综合保险有效期",insuranceDate});
                    if(j == 0){
                        data.put("insuranceName",insuranceName);
                        data.put("insuranceDate",insuranceDate);
                    }
                }
                mapParams.put("insuranceList",insuranceList);
            }

            XmlFill.poiExportNewWord(path,data,null,environment,"/letterOfCommitment.docx",mapParams);
        }catch (Exception e){
            logger.error("生成承诺书文件出现异常！",e);
        }
        return result;
    }

    /**
     * 按需维保申请状态 0: 未提交 1: 审批中 2:审批通过 3: 审批拒绝 4: 已中止 5: 已到期
     * @param map
     * @return
     */
    @Override
    @Transactional
    public Map<String, Object> update(Map map) {
        try{
            demandMaintMapp.update(map);
            /**
             * 按需维保提交审批，发送监管单位管理人员及时审批
             */
            if("1".equals(map.get("applyStatus"))){
                Map<String, Object> param = new HashMap<>();
                param.put("roleName", "%管理人员%");
                param.put("partyId", map.get("parentPartyId"));
                List<String> users = partyMapp.queryUserList(param);

                for (String userId : users) {
                    String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                    MessageNotice msg = new MessageNotice();
                    msg.setTitle("按需维保审批");
                    msg.setContent("您有一份按需维保申请，需要您审核批准，请及时处理！");
                    msg.setReceiveUserId(userId);
                    msg.setIsRead("0");
                    msg.setNoticeTime(noticeTime);
                    msg.setSendUserId(map.get("userPartyId") + "");
                    msg.setReceivePartyId(map.get("parentPartyId") + "");
                    messageNoticeMapp.add(msg);
                }
            }

            /**
             * 按需维保审批完成，告知使用单位管理人员
             */
            if("2".equals(map.get("applyStatus")) || "3".equals(map.get("applyStatus"))){
                if("2".equals(map.get("applyStatus"))){
                    //审批通过，修改当前对应电梯维保周期
                    updateMaintCycle(map);
                }
                sendMessageNotice(map);
            }
            /**
             * 按需维保被中止，告知维保单位与物业单位
             */
            if("4".equals(map.get("applyStatus"))){
                updateMaintCycle(map);
                sendMessageNotice(map);
            }
            return ResultUtil.returnSuccess("更新成功", null);
        }catch (Exception e){
            logger.error("按需维保申请记录更新失败！",e);
            return ResultUtil.returnSuccess("更新失败", null);
        }
    }

    /**
     * 按需维保审批通过、中止给物业与维保单位发送消息
     * @param map
     * @throws Exception
     */
    private void sendMessageNotice(Map map) throws Exception{
        String title = "";
        String content = "";
        if("2".equals(map.get("applyStatus"))){
            title = "按需维保审批通过";
            content = "您有一份按需维保审批通过，请及时查看确认";
        }
        if("3".equals(map.get("applyStatus"))){
            title = "按需维保审批拒绝";
            content = "您有一份按需维保审批拒绝，请及时查看确认";
        }
        if("4".equals(map.get("applyStatus"))){
            title = "按需维保中止";
            content = "您有一份按需维保已经被中止，请及时查看确认";
        }
        //发送使用单位
        Map<String, Object> param1 = new HashMap<>();
        param1.put("roleName", "%管理人员%");
        param1.put("partyId", map.get("userPartyId"));
        List<String> users = partyMapp.queryUserList(param1);

        for (String userId : users) {
            String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            MessageNotice msg = new MessageNotice();
            msg.setTitle(title);
            msg.setContent(content);
            msg.setReceiveUserId(userId);
            msg.setIsRead("0");
            msg.setNoticeTime(noticeTime);
            msg.setSendUserId(map.get("parentPartyId") + "");
            msg.setReceivePartyId(map.get("userPartyId") + "");
            messageNoticeMapp.add(msg);
        }

        //发送维保单位
        Map<String, Object> param2 = new HashMap<>();
        param2.put("roleName", "%管理人员%");
        param2.put("partyId", map.get("maintenancePartyId"));
        List<String> users1 = partyMapp.queryUserList(param2);

        for (String userId : users1) {
            String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            MessageNotice msg = new MessageNotice();
            msg.setTitle(title);
            msg.setContent(content);
            msg.setReceiveUserId(userId);
            msg.setIsRead("0");
            msg.setNoticeTime(noticeTime);
            msg.setSendUserId(map.get("parentPartyId") + "");
            msg.setReceivePartyId(map.get("maintenancePartyId") + "");
            messageNoticeMapp.add(msg);
        }
    }

    /**
     * 按需维保审批通过或者中止，修改维保周期
     */
    private void updateMaintCycle(Map map) throws Exception{
        List<String> elevatorIds = new ArrayList<>();
        if(map.get("elevatorIds") != null && !"".equals(map.get("elevatorIds"))){
            String elevatorIdStr = (String)map.get("elevatorIds");
            elevatorIds = Arrays.asList(elevatorIdStr.split(","));
        }
        int maintenanceDay = 0;
        Map<String,Object> inMap = new HashMap<>();
        if("2".equals(map.get("applyStatus"))){
            if(map.get("maintenanceCycle") != null && !"".equals(map.get("maintenanceCycle"))){
                String maintenanceCycle = (String) map.get("maintenanceCycle");
                if("一个月".equals(maintenanceCycle)){
                    maintenanceDay = 30;
                }
                if("二个月".equals(maintenanceCycle)){
                    maintenanceDay = 60;
                }
                if("三个月".equals(maintenanceCycle)){
                    maintenanceDay = 90;
                }
            }

            inMap.put("isParticipateIn","1");
            inMap.put("maintenanceDay",maintenanceDay);
            inMap.put("elevatorIds",elevatorIds);
        }
        if("4".equals(map.get("applyStatus"))){ //已中止，修改半月保周期为15
            inMap.put("isParticipateIn","0");
            inMap.put("maintenanceDay",15);
            inMap.put("elevatorIds",elevatorIds);
        }

        //保存维保天数,更新下次维保时间
        elevatorMapp.updateElevatorDemandMaintanceDay(inMap);

    }

    @Override
    @Transactional
    public Map<String, Object> delete(Map map) {
        try{
            if(map.get("ids") != null && !"".equals(map.get("ids"))) {
                for (Object id : (List) map.get("ids")) {
                    demandMaintMapp.delete(id + "");
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("删除失败", null);
        }
        return  ResultUtil.returnSuccess("删除成功", null);
    }
}
